package com.zlyx.easy.swagger.plugins;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.core.annotation.Order;

import com.google.common.base.Optional;
import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.swagger.annotations.SpringController;

import io.swagger.annotations.Api;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1)
public class EasySwaggerOperationTagsReader implements OperationBuilderPlugin {

	@Override
	public void apply(OperationContext context) {
		context.operationBuilder().tags(controllerTags(context));
	}

	@SuppressWarnings("deprecation")
	private Set<String> controllerTags(OperationContext context) {
		Optional<SpringController> annotation = context.findControllerAnnotation(SpringController.class);
		Optional<Api> api = context.findControllerAnnotation(Api.class);
		List<String> tags = Arrays.asList(context.getGroupName());
		if (annotation.isPresent() && ObjectUtils.isNotEmpty(annotation.get().todo())) {
			tags = Arrays.asList(annotation.get().todo());
		} else if (api.isPresent() && !api.get().hidden()) {
			if (StringUtils.isNotEmpty(api.get().value())) {
				tags = Arrays.asList(api.get().value());
			} else if (StringUtils.isNotEmpty(api.get().description())) {
				tags = Arrays.asList(api.get().description());
			} else if (ObjectUtils.isNotEmpty(api.get().tags())) {
				tags = Arrays.asList(api.get().tags());
			}
		}
		return new HashSet<>(tags);
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return true;
	}
}
